<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.example.domain.Comment, com.example.domain.Post, com.example.domain.User" %>
<%@ page import="java.util.List" %>
<html>
<head>
    <title>帖子详情</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%);
            min-height: 100vh;
            color: #374151;
        }

        .header {
            background: white;
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
            border-bottom: 1px solid #e2e8f0;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .header-content {
            max-width: 1000px;
            margin: 0 auto;
            padding: 16px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .back-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: transparent;
            border: none;
            color: #3b82f6;
            cursor: pointer;
            border-radius: 20px;
            transition: all 0.3s ease;
            text-decoration: none;
            font-weight: 500;
        }

        .back-btn:hover {
            background: #eff6ff;
            transform: translateY(-2px);
        }

        .nav-links {
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        .nav-links a {
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: 500;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }

        .nav-secondary {
            border-color: #e5e7eb;
            color: #374151 !important;
        }

        .nav-secondary:hover {
            background: #f9fafb;
            border-color: #d1d5db;
            transform: translateY(-2px);
        }

        .nav-ghost {
            color: #6b7280 !important;
        }

        .nav-ghost:hover {
            background: #f3f4f6;
            transform: translateY(-2px);
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 32px 20px;
        }

        .post-detail {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            margin-bottom: 32px;
            overflow: hidden;
        }

        .post-header {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
            padding: 32px;
        }

        .post-title {
            font-size: 28px;
            font-weight: bold;
            margin: 0 0 16px 0;
            line-height: 1.3;
        }

        .post-meta {
            display: flex;
            align-items: center;
            gap: 20px;
            color: rgba(255, 255, 255, 0.9);
            flex-wrap: wrap;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .post-content {
            padding: 32px;
        }

        .post-text {
            color: #374151;
            line-height: 1.8;
            font-size: 16px;
            margin-bottom: 32px;
            white-space: pre-wrap;
        }

        .post-actions {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-top: 24px;
            border-top: 1px solid #e5e7eb;
            flex-wrap: wrap;
            gap: 16px;
        }

        .action-buttons {
            display: flex;
            align-items: center;
            gap: 16px;
            flex-wrap: wrap;
        }

        .like-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px 20px;
            border-radius: 25px;
            border: 2px solid #f472b6;
            background: transparent;
            color: #f472b6;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .like-btn.liked {
            background: linear-gradient(135deg, #f472b6 0%, #ef4444 100%);
            color: white;
            border-color: transparent;
        }

        .like-btn:hover {
            background: linear-gradient(135deg, #f472b6 0%, #ef4444 100%);
            color: white;
            border-color: transparent;
            transform: translateY(-2px);
        }

        .edit-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px 20px;
            border-radius: 25px;
            border: 2px solid #10b981;
            background: transparent;
            color: #10b981;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            text-decoration: none;
        }

        .edit-btn:hover {
            background: #10b981;
            color: white;
            border-color: transparent;
            transform: translateY(-2px);
        }

        .like-display {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #6b7280;
            font-weight: 500;
        }

        .comment-count {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #6b7280;
        }

        .comments-section {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .comments-header {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .comments-header h3 {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
        }

        .comments-content {
            padding: 32px;
        }

        .new-comment-form {
            margin-bottom: 32px;
            padding: 24px;
            background: linear-gradient(135deg, #eff6ff 0%, #f3e8ff 100%);
            border-radius: 16px;
        }

        .form-title {
            font-size: 18px;
            font-weight: 600;
            margin: 0 0 16px 0;
            color: #1f2937;
        }

        .comment-textarea {
            width: 100%;
            min-height: 120px;
            padding: 16px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 16px;
            font-family: inherit;
            resize: vertical;
            margin-bottom: 16px;
            transition: border-color 0.3s ease;
        }

        .comment-textarea:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .submit-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
            border: none;
            border-radius: 25px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        }

        .login-prompt {
            text-align: center;
            padding: 32px;
            background: #f9fafb;
            border-radius: 16px;
            margin-bottom: 32px;
        }

        .login-prompt p {
            color: #6b7280;
            margin: 0 0 16px 0;
            font-size: 16px;
        }

        .login-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
            text-decoration: none;
            border-radius: 25px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        }

        .comment-item {
            margin-bottom: 24px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            border-left: 4px solid #3b82f6;
        }

        .reply-comment {
            margin-left: 48px;
            margin-top: 16px;
            margin-bottom: 16px;
            border-left-color: #10b981;
        }

        .comment-content {
            padding: 24px;
        }

        .comment-header {
            display: flex;
            align-items: flex-start;
            gap: 16px;
            margin-bottom: 16px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 16px;
            flex-shrink: 0;
        }

        .comment-info {
            flex: 1;
        }

        .comment-meta {
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        .username {
            font-weight: 600;
            color: #1f2937;
        }

        .time {
            color: #6b7280;
            font-size: 14px;
        }

        .comment-text {
            color: #374151;
            line-height: 1.6;
            margin-bottom: 16px;
            white-space: pre-wrap;
        }

        .comment-actions {
            display: flex;
            align-items: center;
            gap: 16px;
            flex-wrap: wrap;
        }

        .comment-like-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 20px;
            border: 2px solid #f472b6;
            background: transparent;
            color: #f472b6;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        }

        .comment-like-btn.liked {
            background: linear-gradient(135deg, #f472b6 0%, #ef4444 100%);
            color: white;
            border-color: transparent;
        }

        .comment-like-btn:hover {
            background: linear-gradient(135deg, #f472b6 0%, #ef4444 100%);
            color: white;
            border-color: transparent;
            transform: translateY(-1px);
        }

        .reply-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 20px;
            border: 2px solid #6b7280;
            background: transparent;
            color: #6b7280;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        }

        .reply-btn:hover {
            background: #6b7280;
            color: white;
            transform: translateY(-1px);
        }

        .comment-like-display {
            display: flex;
            align-items: center;
            gap: 6px;
            color: #6b7280;
            font-size: 14px;
        }

        .reply-form {
            margin-top: 16px;
            padding: 16px;
            background: #f9fafb;
            border-radius: 12px;
        }

        .reply-textarea {
            width: 100%;
            min-height: 80px;
            padding: 12px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 14px;
            font-family: inherit;
            resize: vertical;
            margin-bottom: 12px;
            transition: border-color 0.3s ease;
        }

        .reply-textarea:focus {
            outline: none;
            border-color: #3b82f6;
        }

        .reply-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .submit-reply-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .submit-reply-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
        }

        .cancel-reply-btn {
            padding: 8px 16px;
            background: transparent;
            border: 2px solid #e5e7eb;
            color: #6b7280;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .cancel-reply-btn:hover {
            background: #f3f4f6;
            transform: translateY(-1px);
        }

        .empty-comments {
            text-align: center;
            padding: 48px 24px;
            color: #6b7280;
        }

        .empty-icon {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .empty-text {
            font-size: 18px;
            margin: 0;
        }

        .highlight {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            padding: 16px;
            border-radius: 12px;
            border-left: 4px solid #f59e0b;
            animation: highlightPulse 2s ease-in-out;
        }

        @keyframes highlightPulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.02); }
        }

        .message-toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 10px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        }

        .message-toast.show {
            transform: translateX(0);
        }

        .message-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }

        .message-error {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }

        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                text-align: center;
            }

            .post-header {
                padding: 24px 20px;
            }

            .post-title {
                font-size: 24px;
            }

            .post-meta {
                flex-direction: column;
                gap: 8px;
                align-items: flex-start;
            }

            .post-content {
                padding: 24px 20px;
            }

            .post-actions {
                flex-direction: column;
                align-items: flex-start;
            }

            .comments-content {
                padding: 20px;
            }

            .new-comment-form {
                padding: 20px;
            }

            .reply-comment {
                margin-left: 24px;
            }

            .comment-header {
                gap: 12px;
            }

            .user-avatar {
                width: 36px;
                height: 36px;
                font-size: 14px;
            }
        }

        @media (max-width: 480px) {
            .container {
                padding: 20px 16px;
            }

            .post-content {
                padding: 20px;
            }

            .comments-content {
                padding: 16px;
            }

            .new-comment-form {
                padding: 16px;
            }

            .comment-content {
                padding: 16px;
            }
        }
    </style>
</head>
<body>
<%
    Post post = (Post) request.getAttribute("post");
    List<Comment> comments = (List<Comment>) request.getAttribute("comments");
    User currentUser = (User) session.getAttribute("USER_SESSION");
%>

<div class="header">
    <div class="header-content">
        <a href="/main" class="back-btn">
            <span>←</span>
            <span>返回首页</span>
        </a>

        <div class="nav-links">
            <% if (currentUser != null) { %>
            <a href="/user/profile" class="nav-secondary">👤 个人中心</a>
            <a href="/logout" class="nav-ghost">🚪 退出</a>
            <% } else { %>
            <a href="/login" class="nav-secondary">🔑 登录</a>
            <% } %>
        </div>
    </div>
</div>

<div class="container">
    <!-- 帖子详情 -->
    <div class="post-detail">
        <div class="post-header">
            <h2 class="post-title"><%= post.getTitle() %></h2>
            <div class="post-meta">
                <span class="meta-item">
                    <span>👤</span>
                    <strong>作者：</strong> <%= post.getUsername() != null ? post.getUsername() : "用户" + post.getUserId() %>
                </span>
                <span class="meta-item">
                    <span>🕒</span>
                    <strong>发布时间：</strong> <%= post.getCreateTime() %>
                </span>
            </div>
        </div>

        <div class="post-content">
            <div class="post-text"><%= post.getContent() %></div>

            <div class="post-actions">
                <div class="action-buttons">
                    <% if (currentUser != null) { %>
                    <button class="like-btn <%= (post.getIsLiked() != null && post.getIsLiked()) ? "liked" : "" %>"
                            onclick="togglePostLike(<%= post.getId() %>, this)">
                        <span>👍</span>
                        <span>点赞</span>
                        <span class="like-count">(<%= post.getLikeCount() != null ? post.getLikeCount() : 0 %>)</span>
                    </button>

                    <% if (currentUser.getId().equals(post.getUserId())) { %>
                    <a href="/post/edit?id=<%= post.getId() %>" class="edit-btn">
                        <span>✏️</span>
                        <span>编辑帖子</span>
                    </a>
                    <% } %>
                    <% } else { %>
                    <span class="like-display">
                        <span>👍</span>
                        <span>点赞 (<%= post.getLikeCount() != null ? post.getLikeCount() : 0 %>)</span>
                    </span>
                    <% } %>
                </div>

                <div class="comment-count">
                    <span>💬</span>
                    <span><%= comments != null ? comments.size() : 0 %> 条评论</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 评论区 -->
    <div class="comments-section">
        <div class="comments-header">
            <span>💬</span>
            <h3>评论区 (<%= comments != null ? comments.size() : 0 %> 条评论)</h3>
        </div>

        <div class="comments-content">
            <!-- 发表评论表单 -->
            <% if (currentUser != null) { %>
            <div class="new-comment-form">
                <h3 class="form-title">发表评论</h3>
                <form action="/comment/save" method="post">
                    <input type="hidden" name="postId" value="<%= post.getId() %>">
                    <textarea name="content" class="comment-textarea" placeholder="输入评论内容..." required></textarea>
                    <input type="submit" value="📤 发表评论" class="submit-btn">
                </form>
            </div>
            <% } else { %>
            <div class="login-prompt">
                <p>登录后才能发表评论</p>
                <a href="/login" class="login-btn">🔑 立即登录</a>
            </div>
            <% } %>

            <!-- 评论列表 -->
            <%!
                public void renderComment(Comment c, int level, javax.servlet.jsp.JspWriter out, int postId, User currentUser) throws java.io.IOException {
                    String commentClass = level > 0 ? "comment-item reply-comment" : "comment-item";
                    out.write("<div id='comment-" + c.getId() + "' class='" + commentClass + "'>");
                    out.write("<div class='comment-content'>");

                    out.write("<div class='comment-header'>");
                    out.write("<div class='user-avatar'>" + (c.getUsername() != null ? c.getUsername().substring(0, 1).toUpperCase() : "U") + "</div>");
                    out.write("<div class='comment-info'>");
                    out.write("<div class='comment-meta'>");
                    out.write("<span class='username'>" + (c.getUsername() != null ? c.getUsername() : "用户" + c.getUserId()) + "</span>");
                    out.write("<span class='time'>" + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getCreateTime()) + "</span>");
                    out.write("</div>");
                    out.write("</div>");
                    out.write("</div>");

                    out.write("<div class='comment-text'>" + c.getContent() + "</div>");

                    // 评论操作区域
                    out.write("<div class='comment-actions'>");

                    if (currentUser != null) {
                        // 点赞按钮
                        String likedClass = (c.getIsLiked() != null && c.getIsLiked()) ? "liked" : "";
                        int likeCount = c.getLikeCount() != null ? c.getLikeCount() : 0;
                        out.write("<button class='comment-like-btn " + likedClass + "' onclick='toggleCommentLike(" + c.getId() + ", this)'>");
                        out.write("<span>❤️</span><span class='like-count'>" + likeCount + "</span>");
                        out.write("</button>");

                        // 回复按钮
                        if (level == 0) {
                            out.write("<button onclick='toggleReplyForm(" + c.getId() + ")' class='reply-btn'>");
                            out.write("<span>💬</span><span>回复</span>");
                            out.write("</button>");
                        }
                    } else {
                        out.write("<span class='comment-like-display'>");
                        out.write("<span>❤️</span><span>" + (c.getLikeCount() != null ? c.getLikeCount() : 0) + "</span>");
                        out.write("</span>");
                    }

                    out.write("</div>");

                    // 回复表单（默认隐藏）
                    if (currentUser != null && level == 0) {
                        out.write("<div id='reply-form-" + c.getId() + "' class='reply-form' style='display: none;'>");
                        out.write("<form action='/comment/save' method='post'>");
                        out.write("<input type='hidden' name='postId' value='" + postId + "'/>");
                        out.write("<input type='hidden' name='parentId' value='" + c.getId() + "'/>");
                        out.write("<textarea name='content' class='reply-textarea' placeholder='回复该评论...' required></textarea>");
                        out.write("<div class='reply-buttons'>");
                        out.write("<input type='submit' value='📤 发表回复' class='submit-reply-btn'/>");
                        out.write("<button type='button' onclick='toggleReplyForm(" + c.getId() + ")' class='cancel-reply-btn'>取消</button>");
                        out.write("</div>");
                        out.write("</form>");
                        out.write("</div>");
                    }

                    out.write("</div>");

                    if (c.getReplies() != null) {
                        for (Comment reply : c.getReplies()) {
                            renderComment(reply, level + 1, out, postId, currentUser);
                        }
                    }

                    out.write("</div>");
                }
            %>

            <%
                if (comments != null && !comments.isEmpty()) {
                    for (Comment c : comments) {
                        renderComment(c, 0, out, post.getId(), currentUser);
                    }
                } else {
            %>
            <div class="empty-comments">
                <div class="empty-icon">💬</div>
                <p class="empty-text">还没有评论，快来抢沙发吧！</p>
            </div>
            <%
                }
            %>
        </div>
    </div>
</div>

<div id="submitMsg" style="color:red;"></div>
<p style="color:red;"><%= request.getAttribute("msg") == null ? "" : request.getAttribute("msg") %></p>

<script>
    // 帖子点赞功能
    function togglePostLike(postId, button) {
        fetch('/like/post', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'postId=' + postId
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.isLiked) {
                        button.classList.add('liked');
                    } else {
                        button.classList.remove('liked');
                    }

                    const likeCountSpan = button.querySelector('.like-count');
                    likeCountSpan.textContent = '(' + data.likeCount + ')';

                    showMessage(data.message, 'success');
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('操作失败，请重试', 'error');
            });
    }

    // 评论点赞功能
    function toggleCommentLike(commentId, button) {
        fetch('/like/comment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'commentId=' + commentId
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.isLiked) {
                        button.classList.add('liked');
                    } else {
                        button.classList.remove('liked');
                    }

                    const likeCountSpan = button.querySelector('.like-count');
                    likeCountSpan.textContent = data.likeCount;

                    showMessage(data.message, 'success');
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('操作失败，请重试', 'error');
            });
    }

    // 切换回复表单显示/隐藏
    function toggleReplyForm(commentId) {
        const replyForm = document.getElementById('reply-form-' + commentId);
        if (replyForm.style.display === 'none') {
            replyForm.style.display = 'block';
        } else {
            replyForm.style.display = 'none';
        }
    }

    // 显示提示信息
    function showMessage(message, type) {
        const messageDiv = document.createElement('div');
        messageDiv.textContent = message;
        messageDiv.className = 'message-toast message-' + type;

        document.body.appendChild(messageDiv);

        // 显示动画
        setTimeout(() => {
            messageDiv.classList.add('show');
        }, 100);

        // 3秒后移除
        setTimeout(() => {
            messageDiv.classList.remove('show');
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    document.body.removeChild(messageDiv);
                }
            }, 300);
        }, 3000);
    }

    // 页面加载后如果有 #comment-xxx 锚点，则高亮对应评论并滚动过去
    window.onload = function() {
        const hash = window.location.hash;
        if (hash && hash.startsWith("#comment-")) {
            const el = document.querySelector(hash);
            if (el) {
                el.classList.add("highlight");
                el.scrollIntoView({ behavior: "smooth" });
            }
        }
    };
</script>

</body>
</html>
